<template>
  <div class="equipment-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>设备管理</h1>
        <p class="description">管理洗护设备，监控设备状态，记录维护信息</p>
      </div>
      <div class="header-right">
        <el-button type="success" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加设备
        </el-button>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 设备状态总览 -->
    <div class="equipment-overview">
      <div class="overview-card">
        <div class="card-icon idle">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <div class="card-content">
          <h3>{{ equipmentStats.idle || 0 }}</h3>
          <p>空闲设备</p>
        </div>
      </div>
      <div class="overview-card">
        <div class="card-icon running">
          <el-icon><Loading /></el-icon>
        </div>
        <div class="card-content">
          <h3>{{ equipmentStats.running || 0 }}</h3>
          <p>运行中设备</p>
        </div>
      </div>
      <div class="overview-card">
        <div class="card-icon maintenance">
          <el-icon><Tools /></el-icon>
        </div>
        <div class="card-content">
          <h3>{{ equipmentStats.maintenance || 0 }}</h3>
          <p>维护中设备</p>
        </div>
      </div>
      <div class="overview-card">
        <div class="card-icon error">
          <el-icon><WarningFilled /></el-icon>
        </div>
        <div class="card-content">
          <h3>{{ equipmentStats.error || 0 }}</h3>
          <p>故障设备</p>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="设备名称">
          <el-input
            v-model="filterForm.name"
            placeholder="请输入设备名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select
            v-model="filterForm.type"
            placeholder="请选择设备类型"
            clearable
            style="width: 150px"
          >
            <el-option label="洗衣机" value="washing_machine" />
            <el-option label="干洗机" value="dry_cleaning_machine" />
            <el-option label="烘干机" value="dryer" />
            <el-option label="熨烫机" value="ironing_machine" />
            <el-option label="包装机" value="packaging_machine" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(label, value) in EQUIPMENT_STATUS"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 设备列表 -->
    <div class="equipment-grid">
      <div
        v-for="equipment in equipmentList"
        :key="equipment.id"
        class="equipment-card"
        :class="{ 'status-error': equipment.status === 'ERROR' }"
      >
        <div class="equipment-header">
          <div class="equipment-info">
            <h4>{{ equipment.name }}</h4>
            <p class="equipment-model">{{ equipment.model }}</p>
          </div>
          <div class="equipment-status">
            <el-tag
              :type="getStatusTagType(equipment.status)"
              effect="dark"
              size="small"
            >
              {{ EQUIPMENT_STATUS[equipment.status] }}
            </el-tag>
          </div>
        </div>

        <div class="equipment-details">
          <div class="detail-item">
            <span class="label">设备类型:</span>
            <span class="value">{{ getEquipmentTypeLabel(equipment.type) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">购入日期:</span>
            <span class="value">{{ formatDate(equipment.purchaseDate) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">使用年限:</span>
            <span class="value">{{ calculateAge(equipment.purchaseDate) }}年</span>
          </div>
          <div class="detail-item">
            <span class="label">今日使用:</span>
            <span class="value">{{ equipment.todayUsage || 0 }}小时</span>
          </div>
        </div>

        <div class="equipment-metrics">
          <div class="metric">
            <div class="metric-label">利用率</div>
            <div class="metric-value">
              <el-progress
                :percentage="equipment.utilizationRate || 0"
                :stroke-width="6"
                :show-text="false"
                :color="getUtilizationColor(equipment.utilizationRate)"
              />
              <span class="percentage">{{ equipment.utilizationRate || 0 }}%</span>
            </div>
          </div>
          <div class="metric">
            <div class="metric-label">健康状态</div>
            <div class="metric-value">
              <el-progress
                :percentage="equipment.healthScore || 100"
                :stroke-width="6"
                :show-text="false"
                :color="getHealthColor(equipment.healthScore)"
              />
              <span class="percentage">{{ equipment.healthScore || 100 }}%</span>
            </div>
          </div>
        </div>

        <div class="equipment-actions">
          <el-button
            type="primary"
            size="small"
            @click="viewEquipmentDetail(equipment)"
          >
            查看详情
          </el-button>
          <el-button
            v-if="equipment.status === 'IDLE'"
            type="success"
            size="small"
            @click="startEquipment(equipment)"
          >
            启动设备
          </el-button>
          <el-button
            v-if="equipment.status === 'RUNNING'"
            type="warning"
            size="small"
            @click="stopEquipment(equipment)"
          >
            停止设备
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="showMaintenanceDialog(equipment)"
          >
            维护记录
          </el-button>
          <el-dropdown @command="(command) => handleEquipmentAction(equipment, command)">
            <el-button type="primary" size="small">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑设备</el-dropdown-item>
                <el-dropdown-item command="maintenance">安排维护</el-dropdown-item>
                <el-dropdown-item command="usage">使用记录</el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除设备</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[12, 24, 48, 96]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑设备弹窗 -->
    <EquipmentFormDialog
      v-model:visible="formDialogVisible"
      :equipment="selectedEquipment"
      @success="handleFormSuccess"
    />

    <!-- 设备详情弹窗 -->
    <EquipmentDetailDialog
      v-model:visible="detailDialogVisible"
      :equipment="selectedEquipment"
    />

    <!-- 维护记录弹窗 -->
    <MaintenanceRecordDialog
      v-model:visible="maintenanceDialogVisible"
      :equipment="selectedEquipment"
      @success="refreshData"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  CircleCheck,
  Loading,
  Tools,
  WarningFilled,
  ArrowDown
} from '@element-plus/icons-vue'
import {
  getEquipmentList,
  updateEquipmentStatus,
  deleteEquipment,
  EQUIPMENT_STATUS
} from '@/api/laundry'
import EquipmentFormDialog from './components/EquipmentFormDialog.vue'
import EquipmentDetailDialog from './components/EquipmentDetailDialog.vue'
import MaintenanceRecordDialog from './components/MaintenanceRecordDialog.vue'

// 响应式数据
const equipmentList = ref([])
const selectedEquipment = ref(null)
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const maintenanceDialogVisible = ref(false)

// 筛选表单
const filterForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 12,
  total: 0
})

// 设备统计数据
const equipmentStats = ref({
  idle: 0,
  running: 0,
  maintenance: 0,
  error: 0
})

// 设备类型映射
const equipmentTypes = {
  washing_machine: '洗衣机',
  dry_cleaning_machine: '干洗机',
  dryer: '烘干机',
  ironing_machine: '熨烫机',
  packaging_machine: '包装机'
}

// 方法
const getEquipmentTypeLabel = (type) => {
  return equipmentTypes[type] || type
}

const getStatusTagType = (status) => {
  const statusTypes = {
    IDLE: 'success',
    RUNNING: 'primary',
    MAINTENANCE: 'warning',
    ERROR: 'danger',
    OFFLINE: 'info'
  }
  return statusTypes[status] || 'info'
}

const getUtilizationColor = (rate) => {
  if (rate >= 80) return '#67c23a'
  if (rate >= 60) return '#e6a23c'
  return '#f56c6c'
}

const getHealthColor = (score) => {
  if (score >= 80) return '#67c23a'
  if (score >= 60) return '#e6a23c'
  return '#f56c6c'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

const calculateAge = (purchaseDate) => {
  const now = new Date()
  const purchase = new Date(purchaseDate)
  return Math.floor((now - purchase) / (1000 * 60 * 60 * 24 * 365))
}

const loadEquipmentList = async () => {
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      name: filterForm.name,
      type: filterForm.type,
      status: filterForm.status
    }

    const response = await getEquipmentList(params)
    equipmentList.value = response.data.records || []
    pagination.total = response.data.total || 0

    // 计算统计数据
    const stats = { idle: 0, running: 0, maintenance: 0, error: 0 }
    equipmentList.value.forEach(equipment => {
      const status = equipment.status.toLowerCase()
      if (stats.hasOwnProperty(status)) {
        stats[status]++
      }
    })
    equipmentStats.value = stats
  } catch (error) {
    ElMessage.error('获取设备列表失败')
    console.error('Load equipment error:', error)
  }
}

const refreshData = () => {
  loadEquipmentList()
}

const handleSearch = () => {
  pagination.page = 1
  loadEquipmentList()
}

const handleReset = () => {
  Object.assign(filterForm, {
    name: '',
    type: '',
    status: ''
  })
  pagination.page = 1
  loadEquipmentList()
}

const handleSizeChange = (val) => {
  pagination.size = val
  pagination.page = 1
  loadEquipmentList()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  loadEquipmentList()
}

const showAddDialog = () => {
  selectedEquipment.value = null
  formDialogVisible.value = true
}

const viewEquipmentDetail = (equipment) => {
  selectedEquipment.value = equipment
  detailDialogVisible.value = true
}

const showMaintenanceDialog = (equipment) => {
  selectedEquipment.value = equipment
  maintenanceDialogVisible.value = true
}

const startEquipment = async (equipment) => {
  try {
    await updateEquipmentStatus(equipment.id, 'RUNNING', '手动启动设备')
    ElMessage.success('设备启动成功')
    refreshData()
  } catch (error) {
    ElMessage.error('设备启动失败')
    console.error('Start equipment error:', error)
  }
}

const stopEquipment = async (equipment) => {
  try {
    await updateEquipmentStatus(equipment.id, 'IDLE', '手动停止设备')
    ElMessage.success('设备停止成功')
    refreshData()
  } catch (error) {
    ElMessage.error('设备停止失败')
    console.error('Stop equipment error:', error)
  }
}

const handleEquipmentAction = async (equipment, action) => {
  selectedEquipment.value = equipment

  switch (action) {
    case 'edit':
      formDialogVisible.value = true
      break
    case 'maintenance':
      maintenanceDialogVisible.value = true
      break
    case 'usage':
      // 显示使用记录
      viewEquipmentDetail(equipment)
      break
    case 'delete':
      await handleDeleteEquipment(equipment)
      break
  }
}

const handleDeleteEquipment = async (equipment) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除设备 "${equipment.name}" 吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteEquipment(equipment.id)
    ElMessage.success('设备删除成功')
    refreshData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('设备删除失败')
      console.error('Delete equipment error:', error)
    }
  }
}

const handleFormSuccess = () => {
  refreshData()
}

// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.equipment-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-left {
      h1 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2937;
      }

      .description {
        margin: 0;
        color: #6b7280;
        font-size: 14px;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .equipment-overview {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;

    .overview-card {
      display: flex;
      align-items: center;
      padding: 20px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;

      .card-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48px;
        height: 48px;
        border-radius: 12px;
        margin-right: 16px;

        &.idle {
          background: linear-gradient(135deg, #10b981, #059669);
          color: white;
        }

        &.running {
          background: linear-gradient(135deg, #3b82f6, #2563eb);
          color: white;
        }

        &.maintenance {
          background: linear-gradient(135deg, #f59e0b, #d97706);
          color: white;
        }

        &.error {
          background: linear-gradient(135deg, #ef4444, #dc2626);
          color: white;
        }
      }

      .card-content {
        h3 {
          margin: 0 0 4px 0;
          font-size: 24px;
          font-weight: 700;
          color: #1f2937;
        }

        p {
          margin: 0;
          font-size: 14px;
          color: #6b7280;
        }
      }
    }
  }

  .filter-section {
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .equipment-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 30px;

    .equipment-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;
      padding: 20px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        transform: translateY(-2px);
      }

      &.status-error {
        border-color: #f87171;
        box-shadow: 0 1px 3px rgba(248, 113, 113, 0.3);
      }

      .equipment-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;

        .equipment-info {
          h4 {
            margin: 0 0 4px 0;
            font-size: 18px;
            font-weight: 600;
            color: #1f2937;
          }

          .equipment-model {
            margin: 0;
            font-size: 14px;
            color: #6b7280;
          }
        }
      }

      .equipment-details {
        margin-bottom: 16px;

        .detail-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;
          font-size: 14px;

          &:last-child {
            margin-bottom: 0;
          }

          .label {
            color: #6b7280;
          }

          .value {
            color: #1f2937;
            font-weight: 500;
          }
        }
      }

      .equipment-metrics {
        margin-bottom: 20px;

        .metric {
          margin-bottom: 12px;

          &:last-child {
            margin-bottom: 0;
          }

          .metric-label {
            font-size: 12px;
            color: #6b7280;
            margin-bottom: 4px;
          }

          .metric-value {
            display: flex;
            align-items: center;
            gap: 8px;

            .el-progress {
              flex: 1;
            }

            .percentage {
              font-size: 12px;
              font-weight: 600;
              color: #1f2937;
              min-width: 35px;
              text-align: right;
            }
          }
        }
      }

      .equipment-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
  }
}
</style> 